<?php

namespace yiike\goods\backend\controllers;
use yiike\goods\model\GoodsCategory;
use yii\web\HttpException;
use yii\helpers\Url;
use yii\filters\AccessControl;
use dmstr\bootstrap\Tabs;
/**
* This is the class for controller "GoodsCategoryController".
*/
class GoodsCategoryController extends \yiike\goods\backend\controllers\base\GoodsCategoryController
{
    public function actionIndex()
    {
        $model = new GoodsCategory();
        $category = $model->find()->select('id,name,parent_id,logo,banner,orderby,status')->where(['parent_id'=>0])->orderBy(' orderby desc ')->asArray()->all();
        $children = $model->find()->select('id,name,parent_id,logo,banner,orderby,status')->where(['<> ','parent_id',0])->orderBy(' orderby desc ')->asArray()->all();
        Tabs::clearLocalStorage();
        foreach($category as $k=>$v){
            foreach($children as $m=>$n){
                if($v['id']==$n['parent_id']){
                    $v['sub'][] = $n;
                }
            }
            $category[$k] = $v;
        }
        Url::remember();
        \Yii::$app->session['__crudReturnUrl'] = null;
        return $this->render('index', [
            'children'=>$children,
            'category'=>$category
        ]);
    }
    public function actionCreate($parentid)
    {
        $model = new GoodsCategory();
        if($parentid!=0){
            $category = $model->find()->select('name')->where(['id'=>$parentid])->asArray()->one();
            $category = $category['name'];
        }else{
            $category = 0;
        }

        try {
            if ($model->load($_POST)){
                $model->store_id=0;
                $model->weid = 0;
                $model->parent_id = $parentid;
                if($model->save()){
                    return $this->redirect(Url::toRoute('goods-category/index'));
                } elseif (!\Yii::$app->request->isPost) {
                    $model->load($_GET);
                }
            }
        } catch (\Exception $e) {
            $msg = (isset($e->errorInfo[2]))?$e->errorInfo[2]:$e->getMessage();
            $model->addError('_exception', $msg);
        }
        return $this->render('create', ['model' => $model,'category'=>$category]);
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $category = null;
        if ($model->load($_POST) && $model->save()) {
            return $this->redirect(Url::previous());
        } else {
            return $this->render('update', [
                'model' => $model,
                'category'=>$category
            ]);
        }
    }
}
